package platformlog_logic

import (
	"context"
	"fmt"
	"yunzhan/common/models"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryheartbeatsInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryheartbeatsInfoLogic 查询心跳信息
func NewQueryheartbeatsInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryheartbeatsInfoLogic {
	return &QueryheartbeatsInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryheartbeatsInfoLogic) QueryheartbeatsInfo(req *types.QueryHeartbeatsRequest) (resp *types.QueryHeartbeatsResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var selectSQL string
	selectSQL = fmt.Sprintf(`
		SELECT cluster_id, agent_id, hostname, ip_address, status, cpu_usage, memory_usage, disk_space, last_heartbeat, process_count
		FROM %s
		WHERE cluster_id = '%s'`, l.svcCtx.Config.SQLite.Tables.AgentHeartbeats, req.ClusterID)
	if flag {
		selectSQL = fmt.Sprintf(`
		SELECT cluster_id, agent_id, hostname, ip_address, status, cpu_usage, memory_usage, disk_space, last_heartbeat, process_count
		FROM %s
		WHERE cluster_id = '%s'`, l.svcCtx.Config.Mysql.Tables.AgentHeartbeats, req.ClusterID)
	}

	// 构建查询条件
	var params []interface{}
	if req.AgentId != "" {
		selectSQL += " AND agent_id = ?"
		params = append(params, req.AgentId)
	}
	if req.HostName != "" {
		selectSQL += " AND hostname = ?"
		params = append(params, req.HostName)
	}
	if req.IPAddress != "" {
		selectSQL += " AND ip_address = ?"
		params = append(params, req.IPAddress)
	}
	if req.Status {
		selectSQL += " AND status = ?"
		params = append(params, req.Status)
	}

	selectSQL += " ORDER BY last_heartbeat DESC"

	var heartbeatInfos []models.HeartbeatInfo
	err = l.svcCtx.Conn.QueryRows(&heartbeatInfos, selectSQL, params...)
	if err != nil {
		logx.Errorf("failed to query heartbeats info: %v", err)
		return nil, err
	}

	return &types.QueryHeartbeatsResponse{
		Code:    200,
		Message: "查询心跳信息成功",
		Data:    heartbeatInfos,
	}, nil
}
